package com.ruoyi.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.KongAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service("BlackListKong")
public class BlackListKong {
    @Autowired
    KongAdmin kongAdmin;
    @Value("${iprestriction}")
    String IPRestriction;
    public String addBlackList(String ip) {
        String result = "";
//        System.out.println("kkkkkkkkkkk"+IPRestriction);
        String info=kongAdmin.getIt("plugins/"+IPRestriction);
        JSONObject infojson = JSONObject.parseObject(info);
        JSONObject config = infojson.getJSONObject("config");
        if (config.getJSONArray("deny")==null) {
            JSONArray deny = new JSONArray();
            deny.add(ip);
            config.put("deny", deny);
        } else {
            config.getJSONArray("deny").add(ip);
        }
        JSONObject requestBody = new JSONObject();
        requestBody.put("name","ip-restriction");
        requestBody.put("config",config);
     result=kongAdmin.PatchPlugin(IPRestriction,requestBody);
        return result;
    }

    public String delBlackList(String ip) {
        String result = "";
        String info=kongAdmin.getIt("plugins/"+IPRestriction);
        JSONObject infojson = JSONObject.parseObject(info);
        JSONObject config = infojson.getJSONObject("config");
        if (config.getJSONArray("deny")==null) {
          return "500";
        } else {
            config.getJSONArray("deny").remove(ip);
        }
        JSONObject requestBody = new JSONObject();
        requestBody.put("name","ip-restriction");
        requestBody.put("config",config);
        result=kongAdmin.PatchPlugin(IPRestriction,requestBody);
        return result;
    }
}
